﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MINERP.BLL.GoodsDelivery;
using MINERP.COM;

namespace ERPGoodsDelivery.Return
{
    public partial class FrmGetReturnPackage : Form
    {
        //属性
        private static FrmGetReturnPackage _instance;
        public static FrmGetReturnPackage GetInstance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new FrmGetReturnPackage();
                }
                return _instance;
            }
            set
            {
                _instance = value;
            }
        }
        //参数
        private GoodsReturnBLL bll = new GoodsReturnBLL();
        private GoodsDeliveryBLL userBll = new GoodsDeliveryBLL();

        //int
        private int CurrentReturnInfoId = 0;                                //当前有效的退件产品Id
        private int ReturnOrderInfoIdNotFetch = 0;                          //当前的退件产品Id(未取件)
        //bool
        //private bool canModify = false;                                     //能否修改未取件的退件产品

        public FrmGetReturnPackage()
        {
            InitializeComponent();
        }

        private void FrmGetReturnPackage_Load(object sender, EventArgs e)
        {
            SetDefaultTime();
            BindReturnPackageNotFectch();
            BindFetchUser();

            //BindReturnPackageFetched();
        }

        //单击
        private void gvReturnPackage_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            int returnId = Convert.ToInt32(gvReturnPackage.GetRowCellValue(e.RowHandle, "ReturnId"));
            BindLbOrderInfos(returnId);
            tsSaveReturnInfo.Enabled = false;
            SetEnableOrNotEnable(false);
        }
        //焦点变化
        private void gvReturnPackage_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle >= 0)
            {
                int returnId = Convert.ToInt32(gvReturnPackage.GetRowCellValue(e.FocusedRowHandle, "ReturnId"));
                BindLbOrderInfos(returnId);
                tsSaveReturnInfo.Enabled = false;
                SetEnableOrNotEnable(false);
            }
        }

        //新增退件产品
        private void tsSaveReturnInfo_Click(object sender, EventArgs e)
        {
            try
            {
                int returnId = Convert.ToInt32(gvReturnPackage.GetDataRow(gvReturnPackage.GetSelectedRows()[0])["ReturnId"]);
                int fetchUsesrId = Convert.ToInt32(cbUser.SelectedValue);
                string returnReason = txtReturnReason.Text;
                bll.InsertReturnOrderInfo(returnId, CurrentReturnInfoId, fetchUsesrId, returnReason);
                tsSaveReturnInfo.Enabled = false;
                txtOrderProductId.Text = "";
                BindLbOrderInfos(returnId);
                SetOrderInfoBack();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        //产品验证
        private void btnOrderInfo_Click(object sender, EventArgs e)
        {
            try
            {
                //产品不存在或产品编号已存在于退件包内
                string productCode = txtOrderProductId.Text.Trim();
                if (productCode == null || productCode.Length == 0)
                {
                    MessageBox.Show("产品号不能为空！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtOrderProductId.SelectAll();
                    txtOrderProductId.Focus();
                    tsSaveReturnInfo.Enabled = false;
                    return;
                }
                foreach (object obj in lbOrderInfos.Items)
                {
                    if (obj.ToString() == productCode)
                    {
                        MessageBox.Show("产品已退件！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtOrderProductId.SelectAll();
                        txtOrderProductId.Focus();
                        tsSaveReturnInfo.Enabled = false;
                        return;
                    }
                }
                int orderProductId = 0;
                try
                {
                    orderProductId = Convert.ToInt32(productCode);
                }
                catch
                {
                    MessageBox.Show("请输入正确的产品号(不要全部输入，只要最后几位即可)", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtOrderProductId.SelectAll();
                    txtOrderProductId.Focus();
                    tsSaveReturnInfo.Enabled = false;
                    return;
                }
                GoodsReturnBLL.OrderInfoConfirm info = bll.ConfirmOrderInfo(orderProductId);
                if (info.OrderProductId == 0)
                {
                    MessageBox.Show("产品不存在！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtOrderProductId.SelectAll();
                    txtOrderProductId.Focus();
                    tsSaveReturnInfo.Enabled = false;
                    return;
                }
                if (DialogResult.Yes == MessageBox.Show("退件的产品为(商户名：" + info.ShopName + "|客户名：" + info.CtmName + "|产品名：" + info.OrderProductName + ")，继续吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                {
                    tsSaveReturnInfo.Enabled = true;
                    CurrentReturnInfoId = info.OrderProductId;              //保存退件产品Id(防止在保存前界面上退件产品Id发生了变化)
                    SetOrderInfo(info.ShopName,info.CtmName,info.OrderProductName);
                }
                else
                {
                    tsSaveReturnInfo.Enabled = false;
                    SetOrderInfoBack();
                }
            }
            catch (Exception ex)
            {
                tsSaveReturnInfo.Enabled = false;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //修改未取件的退件产品
        private void btnModify_Click(object sender, EventArgs e)
        {
            try
            {
                if (lbOrderInfos.SelectedItems != null && lbOrderInfos.SelectedItems.Count > 0)
                {
                    //canModify = true;
                    SetEnableOrNotEnable(true);         //能用
                    int returnId = Convert.ToInt32(gvReturnPackage.GetRowCellValue(gvReturnPackage.GetSelectedRows()[0], "ReturnId")) ;
                    int orderProductId = Convert.ToInt32(lbOrderInfos.SelectedItems[0]);
                    SetReturnInfo(returnId, orderProductId);
                    tsSaveReturnInfo.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //修改未取件的退件产品(保存)
        private void btnSaveInfo_Click(object sender, EventArgs e)
        {
            try
            {
                int fetchUserId = Convert.ToInt32(cbUser.SelectedValue);
                string returnReason = txtReturnReason.Text;
                bll.ModifyReturnOrderInfo(ReturnOrderInfoIdNotFetch, fetchUserId, returnReason);
                MessageBox.Show("修改成功！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                SetEnableOrNotEnable(false);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        //修改未取件的退件产品(取消)
        private void btnCanInfo_Click(object sender, EventArgs e)
        {
            SetEnableOrNotEnable(false);
            SetOrderInfoBack();
        }
        
        //删除未取件的退件产品
        private void btnDel_Click(object sender, EventArgs e)
        {
            try
            {
                if (lbOrderInfos.Items == null || lbOrderInfos.Items.Count == 0)
                    return;
                if (DialogResult.Yes == MessageBox.Show("确定要删除该退件产品吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                {
                    int returnId = Convert.ToInt32(gvReturnPackage.GetRowCellValue(gvReturnPackage.GetSelectedRows()[0], "ReturnId"));
                    int orderProductId = Convert.ToInt32(lbOrderInfos.SelectedItems[0]);
                    DelReturnInfo(returnId, orderProductId);
                    SetEnableOrNotEnable(false);         //不能用
                    BindLbOrderInfos(returnId);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        //修改退件包状态为"已取件"
        private void tsModifyReturnPackage_Click(object sender, EventArgs e)
        {
            try
            {
                if (gvReturnPackage.SelectedRowsCount == 0)
                {
                    MessageBox.Show("无退件包被选中！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (DialogResult.Yes == MessageBox.Show("确定要将选中的退件包状态改为“已取件”吗？","确认",MessageBoxButtons.YesNo,MessageBoxIcon.Warning))
                {
                    int returnPackageStatus = (int)ReturnPackageStatus.Fetched;
                    int returnOrderInfoStatus = (int)ReturnOrderInfoStatus.Fetched;
                    int returnId = Convert.ToInt32(gvReturnPackage.GetRowCellValue(gvReturnPackage.GetSelectedRows()[0], "ReturnId"));
                    bll.ModifyReturnPackageStatusToFetch(returnPackageStatus, returnOrderInfoStatus, returnId);
                    BindReturnPackageNotFectch();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //产品列表变化
        private void lbOrderInfos_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                SetEnableOrNotEnable(false);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //刷新未取件退件包
        private void tsRefreshNotFetch_Click(object sender, EventArgs e)
        {
            try
            {
                BindReturnPackageNotFectch();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //tab
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (tabControl1.SelectedTab.Name == "tpNotFetch")
                {
                    BindReturnPackageNotFectch();
                }
                else if (tabControl1.SelectedTab.Name == "tpFetched")
                {
                    BindReturnPackageFetched();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        //----------------------已取件-----------------------
        //单击
        private void gvReturnPackageFetched_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            try
            {
                int returnId = Convert.ToInt32(gvReturnPackageFetched.GetRowCellValue(e.RowHandle, "ReturnId"));
                BindReturnOrderInfosFetched(returnId);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //焦点改变
        private void gvReturnPackageFetched_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                if (e.FocusedRowHandle >= 0)
                {
                    int returnId = Convert.ToInt32(gvReturnPackageFetched.GetRowCellValue(e.FocusedRowHandle, "ReturnId"));
                    BindReturnOrderInfosFetched(returnId);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        //刷新已取件
        private void tsRefreshFetched_Click(object sender, EventArgs e)
        {
            try
            {
                BindReturnPackageFetched();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //修改退件包状态为未取件
        private void tsModifyReturnPackage2_Click(object sender, EventArgs e)
        {
            try
            {
                if (gvReturnPackageFetched.SelectedRowsCount == 0)
                {
                    MessageBox.Show("无退件包被选中！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (DialogResult.Yes == MessageBox.Show("确定要将选中的退件包状态改为“未取件”吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                {
                    int returnId = Convert.ToInt32(gvReturnPackageFetched.GetRowCellValue(gvReturnPackageFetched.GetSelectedRows()[0], "ReturnId"));
                    UpdateReturnPackageToNotFetch(returnId);
                    BindReturnPackageFetched();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //确认键
        private void btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                BindReturnPackageFetched();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //---------------------公共方法-----------------------
        #region 绑定未取件的退件包
        /// <summary>
        /// 绑定未取件的退件包
        /// </summary>
        private void BindReturnPackageNotFectch()
        {
            try
            {
                int notFetch = (int)ReturnPackageStatus.NotFetch;
                DataTable dt = bll.GetReturnPackage(notFetch);
                gcReturnPackage.DataSource = dt;
                gcReturnPackage.RefreshDataSource();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        private void BindFetchUser()
        {
            try
            {
                DataTable dt = userBll.GetDeliveryWorkers();
                cbUser.DisplayMember = "UserName";
                cbUser.ValueMember = "UserId";
                cbUser.DataSource = dt;
                cbUser.Text = "";
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void BindLbOrderInfos(int returnId)
        {
            try
            {
                List<int> orderProductIds = bll.GetOrderProductIdsInReturnPackage(returnId);
                lbOrderInfos.DataSource = orderProductIds;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 保存与取消未取件产品是否可用
        /// </summary>
        /// <param name="enable"></param>
        private void SetEnableOrNotEnable(bool enable)
        {
            if (enable)
            {
                txtOrderProductId.Enabled = false;
                btnSaveInfo.Enabled = true;
                btnCanInfo.Enabled = true;
            }
            else
            {
                txtOrderProductId.Enabled = true;
                btnSaveInfo.Enabled = false ;
                btnCanInfo.Enabled = false;
            }
        }

        /// <summary>
        /// 设置未取件的退件产品
        /// </summary>
        /// <param name="returnId"></param>
        /// <param name="orderProductId"></param>
        private void SetReturnInfo(int returnId, int orderProductId)
        {
            try
            {
                GoodsReturnBLL.ReturnOrderInfo info = bll.GetReturnOrderInfo(returnId, orderProductId);
                txtOrderProductId.Text = info.OrderProductId.ToString();
                cbUser.SelectedValue = info.FetchUserId;
                txtReturnReason.Text = info.ReturnReason;
                ReturnOrderInfoIdNotFetch = info.ReturnInfoId;
                SetOrderInfo(info.ShopName, info.CtmName, info.OrderProductName);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region　删除退件产品
        /// <summary>
        /// 删除退件产品
        /// </summary>
        /// <param name="returnId"></param>
        /// <param name="orderProductId"></param>
        private void DelReturnInfo(int returnId, int orderProductId)
        {
            try
            {
                bll.DelReturnOrderInfo(returnId, orderProductId);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        //------------已取件--------------
        private void BindReturnPackageFetched()
        {
            try
            {
                int fetched = (int)ReturnPackageStatus.Fetched;
                DateTime start = dtStart.Value;
                DateTime end = dtEnd.Value;
                DataTable dt = bll.GetReturnPackageFetched(fetched,start,end);
                gcReturnPackageFetched.DataSource = dt;
                gcReturnPackageFetched.RefreshDataSource();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void BindReturnOrderInfosFetched(int returnId)
        {
            try
            {
                List<GoodsReturnBLL.ReturnOrderInfo> infos = bll.GetReturnOrderInfos(returnId);
                gcReturnOrderInfo.DataSource = infos;
                gcReturnOrderInfo.RefreshDataSource();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void UpdateReturnPackageToNotFetch(int returnId)
        {
            try
            {
                int status = (int)ReturnPackageStatus.NotFetch;
                bll.UpdateReturnPackageStatus(returnId, status);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void SetDefaultTime()
        {
            dtStart.Value = DateTime.Now.AddDays(-10);
            dtEnd.Value = DateTime.Now.AddDays(1);
        }

        private void SetOrderInfo(string shopName,string ctmName,string orderProductName)
        {
            lblShopName.Text = shopName;
            lblCtmName.Text = ctmName;
            lblOrderProductName.Text = orderProductName;
        }

        private void SetOrderInfoBack()
        {
            lblShopName.Text = "无";
            lblCtmName.Text = "无";
            lblOrderProductName.Text = "无";
        }

    }
}
